package me.flyray.bsin.gateway.service;

import com.alipay.sofa.common.utils.StringUtil;

import me.flyray.bsin.gateway.config.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.log4j.Log4j2;
import me.flyray.bsin.constants.ResponseCode;
import me.flyray.bsin.context.LoginInfoContextHelper;
import me.flyray.bsin.enums.CustomerType;
import me.flyray.bsin.exception.BusinessException;
import me.flyray.bsin.gateway.common.ApiResult;
import me.flyray.bsin.gateway.context.BsinContextBuilder;
import me.flyray.bsin.oss.ipfs.BsinIpfsService;
import me.flyray.bsin.utils.BsinServiceInvokeUtil;

@Log4j2
@Service
public class BsinIpfsRequestHandlerService {

    @Value("${bsin.s11edao.ipfs.api}")
    private String ipfsApi;
    @Value("${bsin.s11edao.ipfs.gateway}")
    private String ipfsGateway;
    @Autowired
    private BsinServiceInvokeUtil bsinServiceInvokeUtil;
    @Autowired
    private BsinIpfsService bsinIpfsService;
    @Autowired
    private MessageProperties config;

    public ApiResult ipfsRequestHandler(String methodName, Map<String, Object> bizParams) throws IOException {
        String currentPath = (String) bizParams.get("currentPath");
        if ("makeDirectory".equals(methodName)) {
            String fileName = (String) bizParams.get("fileName");
            String fileCode = (String) bizParams.get("fileCode");
            String tenantAppType = (String) bizParams.get("tenantAppType");
            String fileDescription = (String) bizParams.get("fileDescription");
            String tenantId = LoginInfoContextHelper.getTenantId();
            if (tenantId == null){
                throw new BusinessException(ResponseCode.TENANT_ID_NOT_ISNULL);
            }
            String merchantNo = LoginInfoContextHelper.getMerchantNo();
            String customerNo = LoginInfoContextHelper.getCustomerNo();
            String userType = LoginInfoContextHelper.getUserType();

            // 根据用户类型判断用户属于哪个平台
            String dev = "bigan-ipfs";
            if (tenantAppType != null) {
                dev = tenantAppType+"-ipfs";
            }

            String tmpRelativePath = "";
            if (tenantId != null) {
                tenantId += tenantId + "/";
            }
            if (merchantNo != null) {
                tmpRelativePath += merchantNo + "/";
            }
            if (customerNo != null) {
                tmpRelativePath += customerNo + "/";
            }
            if (currentPath != null) {
                currentPath = tmpRelativePath + currentPath + "/";
            } else {
                currentPath = tmpRelativePath;
            }
            String absolutePath = "/" + dev + "/" + currentPath;
            try {
                // TODO 判断文件夹是否存在
                bsinIpfsService.mkDir(absolutePath);
            } catch (Exception e) {
                log.error(e.toString());
            }
            String fileAddress;
            try {
                fileAddress = bsinIpfsService.mkDir(absolutePath+fileName);
            } catch (Exception e) {
                log.error(e.toString());
                // 文件夹名称重复
//                throw new BusinessException(ResponseCode.IPFS_DIR_IS_EXISTS);
                throw new BusinessException("100000",e.toString());

            }
            // 创建数据库数据
            Map<String, Object> requestMap = new HashMap<>();

            Map<String, Object> loginMap = BsinContextBuilder.buildLoginContextMap();
            if (ObjectUtil.isNotEmpty(loginMap)) {
                requestMap.put("headers", loginMap);
            }
            requestMap.put("tenantId", tenantId);
            requestMap.put("fileName", fileName);
            requestMap.put("customerNo", customerNo);
            requestMap.put("fileUrl", fileAddress);
            requestMap.put("fileCode", fileCode);
            requestMap.put("fileDescription", fileDescription);
            Map map = bsinServiceInvokeUtil.genericInvoke("MetadataFileService", "makeDirectory", "1.0", requestMap);
            return ApiResult.ok();
        }

        /*if ("ipfsLs".equals(methodName)) {
            String tenantId = (String) BaseContextHandler.get("tenantId");
            String customerType = (String) BaseContextHandler.get("customerType");
            // 根据用户类型判断用户属于哪个平台
            String dev = "bigan";
            if (CustomerType.TENANT_DAO.getCode().equals(customerType)) {
                dev = "daobook";
            }

            if (currentPath == null || currentPath.isEmpty()) {
                currentPath = "/" + dev + "/" + tenantId;
            } else {
                currentPath = "/" + dev + "/" + tenantId + "/" + currentPath;
            }

            String hashDir = this.fileStat(currentPath).get("Hash").toString();
            JSONObject result = this.fileLS(hashDir);
            return ApiResult.ok(result);
        }*/
        return null;
    }
}
